package com.qf.smartdevice.service.impl;

import com.qf.smartdevice.cache.SceneCache;
import com.qf.smartdevice.events.enums.CheckType;
import com.qf.smartdevice.exception.AddDataException;
import com.qf.smartdevice.exception.ErrorCode;
import com.qf.smartdevice.exception.QueryDataException;
import com.qf.smartdevice.mapper.SysSceneMapper;
import com.qf.smartdevice.pojo.SysScene;
import com.qf.smartdevice.pojo.SysUserInfo;
import com.qf.smartdevice.service.SysSceneService;
import com.qf.smartdevice.utils.LoginUserInfoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;

/**
 * @author 王博康
 * @version 1.0
 * @project devicemanagementsystem
 * @description: TODO
 * @date 2022/3/22 16:47 星期二
 */
@Service
@Transactional
public class SysSceneServiceImpl implements SysSceneService {

    private SceneCache sceneCache;

    @Autowired
    public void setSceneCache(SceneCache sceneCache) {
        this.sceneCache = sceneCache;
    }

    private SysSceneMapper sysSceneMapper;

    @Autowired
    public void setSysSceneMapper(SysSceneMapper sysSceneMapper) {
        this.sysSceneMapper = sysSceneMapper;
    }

    @Override
    public int addScene(SysScene sysScene) {
        //判空
        Assert.isTrue(sysScene.isEmpty(CheckType.ADD),()->{
            throw new AddDataException("数据为空", ErrorCode.DATA_NULL);
        } );
        //检查登录
        SysUserInfo loginUser = LoginUserInfoUtil.getLoginUser();
        Assert.notNull(loginUser,()->{
            throw new AddDataException("未登录",ErrorCode.NOT_LOGIN );
        } );
        //同一用户不可创建相同场景
        SysScene scene=sysSceneMapper.findByUserAndName(loginUser.getUId(),sysScene.getSceneName());
        //判断场景不存在或删除状态
        Assert.isTrue(scene==null||scene.getStatus()==0,()->{
            throw new AddDataException("场景已存在",ErrorCode.DATA_ALREADY_EXIST );
        } );
        if (scene==null){//没有数据,创建添加
            //设置其他信息
            sysScene.setCreateBy(loginUser.getUId());
            sysScene.setCreateTime(new Date());
            //操作数据库
            int count=sysSceneMapper.addScene(sysScene);
            return count;
        }else {//修改激活
            int count=sysSceneMapper.updateScene(scene.getSceneId(),1L);
            return count;
        }
    }

    @Override
    public SysScene findById(Long id) {
        //先判断是否登录
        SysUserInfo loginUser = LoginUserInfoUtil.getLoginUser();
        Assert.notNull(loginUser,()->{
            throw new QueryDataException("未登录",ErrorCode.NOT_LOGIN );
        } );

        //先根据主键从缓存中查询到数据
        SysScene scene = sceneCache.get(id);
        //判断是否是登录用户的场景
        Assert.isTrue(scene!=null&&scene.getCreateBy()==loginUser.getUId(),()->{
            throw new QueryDataException("数据不存在",ErrorCode.DATA_NULL );
        } );

        return scene;
    }
}
